package com.sjt.ForkJoinDemo;

import com.sun.scenario.effect.impl.sw.java.JSWColorAdjustPeer;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.*;

@Slf4j
public class test {
    public static void main(String[] args) {
        Random random=new Random();
         int count=10000000;
        int[] a=new int[count];
        int[] b=new int[count];
        for(int i=0;i<count;i++)
        {
            a[i] = random.nextInt(count);
            b[i]=a[i];
        }
        ForkJoinPool pool=new ForkJoinPool();

        QuickSort quickSort=new QuickSort(b,0,count-1);

        long beginTime = System.currentTimeMillis();

        ForkJoinTask<Void> task = pool.submit(quickSort);

        try {
            task.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("fork/join:"+(System.currentTimeMillis()-beginTime)+"ms");

        for(int i=1;i<count;i++)
            if(b[i]<b[i-1])
                throw new RuntimeException();

        long startTime = System.currentTimeMillis();
        Arrays.sort(a);
        System.out.println("sort:"+(System.currentTimeMillis()-startTime)+"ms");
    }

    static class QuickSort extends RecursiveAction {

        private int[]data;
        private int left;
        private int right;
        private int start;
        private int end;

        public QuickSort(int[] data, int left, int right) {
            this.data = data;
            this.left = left;
            this.right = right;
            this.start=left;
            this.end=right;
        }

        @Override
        protected void compute() {

            if(left>=right)
                return;

            int base=data[left];
            while(left<right)
            {
                while(left<right&&data[right]>=base)
                    right--;
                swap(data,left,right);
                while(left<right&&data[left]<=base)
                    left++;
                swap(data,left,right);
            }
            base=left;
            QuickSort task1=null;
            QuickSort task2=null;

            task1 = new QuickSort(data, start, base - 1);
            task1.fork();
            task2 = new QuickSort(data, base + 1, end);
            task2.fork();

            task1.join();
            task2.join();
        }
        public void swap(int[]data,int left,int right)
        {
            int k=data[left];
            data[left]=data[right];
            data[right]=k;
        }
    }
}
